package com.zhiyume.api.controller;

import com.zhiyume.controller.BaseController;
import com.zhiyume.dto.BaseResponse;
import com.zhiyume.dto.LoginResDTO;
import com.zhiyume.service.OauthLoginService;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.OSSClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiaxz
 * @date 2017/11/29 20:43
 * @description
 */
@RestController
@Api(tags = "微信认证相关")
public class OauthWeiXinAction extends BaseController {
    @Autowired
    private OauthLoginService oauthLoginService;

    private static final Logger logger = LoggerFactory.getLogger(OauthWeiXinAction.class);

    @RequestMapping(value = "/api/client/oauthLogin", method = RequestMethod.POST)
    @ApiOperation(value = "微信认证登录接口")
    @ResponseBody
    public BaseResponse oauthWeiXinClientLogin(@RequestParam(defaultValue = "") String openid,
                                               @RequestParam(defaultValue = "") String headimgurl,
                                               @RequestParam(defaultValue = "") String nickname,
                                               @RequestParam(defaultValue = "0") String oauthType, HttpServletResponse response) {
        //判断参数是否为空
        BaseResponse res = new BaseResponse();
        if (StringUtil.isBlank(openid) || "0".equals(oauthType)) {
            res.setErrType(ConstantEnum.CONSTANT_MISS_PARA.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_MISS_PARA.getErrMsg());
            return res;
        }
        String imgUrl = "";
//        imgUrl = getAliObjString(openid, headimgurl);
        imgUrl = headimgurl;
        LoginResDTO dto = null;
        dto = oauthLoginService.oauthLogin(openid, oauthType, nickname, imgUrl);
        if (null == dto || !(dto.getuId() > 0)) {
            res.setErrType(ConstantEnum.CONSTANT_SYS_ERROR.getErrType());
            res.setErrMsg(ConstantEnum.CONSTANT_SYS_ERROR.getErrMsg());
            return res;
        }
        Map<String, Object> cookies = new HashMap<>();
        cookies.put("token", dto.getToken());
        cookies.put("uid", dto.getuId());
        addCookies(response, cookies, null);
        List<LoginResDTO> data = new ArrayList<>();
        data.add(dto);
        res.setData(data);
        res.setErrType(ConstantEnum.CONSTANT_SUCCESS.getErrType());
        res.setErrMsg(ConstantEnum.CONSTANT_SUCCESS.getErrMsg());
        return res;
    }

    private String getAliObjString(String openid, String headimgurl) {
        String imgUrl = "";
        if(StringUtil.isNotBlank(headimgurl)) {
            HttpURLConnection httpconn = null;
            try {
                int HttpResult = 0; // 服务器返回的状态
                URL url = new URL(headimgurl); // 创建URL
                URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
                urlconn.connect();
                httpconn = (HttpURLConnection) urlconn;
                HttpResult = httpconn.getResponseCode();
                System.out.println(HttpResult);
                String type = "png";
                if (HttpResult == HttpURLConnection.HTTP_OK) // 不等于HTTP_OK则连接不成功
                {
                    type =  urlconn.getContentType().split("/")[1];
                    InputStream is = urlconn.getInputStream();
                    System.out.println(type);
                    // File file = FileInputStream
                    //  BufferedImage image = ImageIO.read(io);
                    OSSClientUtil ossClientUtil = new OSSClientUtil("oauthHeadImage/");
                    String md5Str=  ossClientUtil.uploadFile2OSS(is,openid+"."+type);
                    imgUrl = ossClientUtil.getUrl("");
                    System.out.println(">>>>>>>>>>上传文件至阿里云返回串<<<<<<<<<"+md5Str);

                    System.out.println("------图片上传至阿里云的访问地址为---------" + imgUrl);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(null!=httpconn){
                    httpconn.disconnect();
                }
            }
        }
        return imgUrl;
    }
}
